package com.echo.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.activeandroid.query.Select;
import com.echo.model.DayData;
import com.echo.model.DayStep;
import com.echo.service.StepDetector;
import com.echo.service.StepService;
import com.echo.util.DateUtil;

import java.util.Calendar;

public class DateChangeReceiver extends BroadcastReceiver {
    private StepService mServiece;

    public DateChangeReceiver() {
    }

    public DateChangeReceiver(StepService service){
        this.mServiece=service;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        if(intent.getAction().equals(Intent.ACTION_DATE_CHANGED)){

            int steps= StepDetector.CURRENT_SETP;
            DayData dayData=new Select()
                    .from(DayData.class)
                    .where("date=?", DateUtil.getDateStr(DateUtil.getBeforeDay(Calendar.getInstance())))
                    .orderBy("RANDOM()")
                    .executeSingle();
            if(dayData!=null){
                dayData.setSteps(steps);
                dayData.save();
            }else{
                dayData=new DayData();
                dayData.setDate(DateUtil.getDateStr(DateUtil.getBeforeDay(Calendar.getInstance())));
                dayData.setSteps(steps);
                dayData.save();
            }
            StepDetector.CURRENT_SETP=0;
        }
    }
}
